package com.pn.servlet;

import com.pn.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/login")
public class UserServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //1:接收数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        //2:处理请求
        boolean flag = false;
        if("admin".equals(username) && "123456".equals(password)){
            flag = true;
        }

        HttpSession session = req.getSession();
        //3:给出响应
        if(flag){
            //3.1:将查到的用户信息保存在session中
            session.setAttribute("user",new User(username,password,"张三","西安",25));
            //3.2:重定向到index.jsp
            resp.sendRedirect("index.jsp");
        }else{
            //3.1:将错误信息保存在request中
            req.setAttribute("error","用户名或密码有误");
            //3.2:转发到到login.jsp
           req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
}
